package com.yu.handler;

import com.yu.apiutils.ApiResult;
import com.yu.apiutils.ApiResultUtils;
import com.yu.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice// 全局异常处理
public class GlobalExceptionHandler {

    /**
     * 统一处理异常
     *
     * @param e 异常
     * @return API请求响应实体
     */
    @ExceptionHandler(Throwable.class)// 捕获所有异常
    public ApiResult handleException(Throwable e) {
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            log.info("请求中出现业务异常：", e);
            return ApiResultUtils.error(businessException.getCode(), businessException.getMessage());
        }
        log.error("请求中出现系统异常：", e);
        return ApiResultUtils.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器出错啦~");
    }
}